/*
 * HomeServlet.java
 * 作用：首页控制器，负责获取并显示所有上架商品，支持分页。
 */
package com.campustradingwall.controller;

import com.campustradingwall.dao.ProductDao;
import com.campustradingwall.model.Product;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@WebServlet(name = "HomeServlet", urlPatterns = {"","/index"})
public class HomeServlet extends HttpServlet {
    private ProductDao productDao = new ProductDao();
    private static final int PRODUCTS_PER_PAGE = 9; // 每页显示9个商品

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String pageStr = request.getParameter("page");
        String keyword = request.getParameter("keyword"); // 获取搜索关键词

        int currentPage = 1;
        if (pageStr != null && !pageStr.isEmpty()) {
            try {
                currentPage = Integer.parseInt(pageStr);
            } catch (NumberFormatException e) {
                // 如果参数不是有效数字，则默认为第一页
                currentPage = 1;
            }
        }

        int totalProducts = productDao.getOnShelfProductCount(keyword); // 传递关键词给DAO
        int totalPages = (int) Math.ceil((double) totalProducts / PRODUCTS_PER_PAGE);

        // 确保页码在有效范围内
        if (currentPage < 1) {
            currentPage = 1;
        }
        if (currentPage > totalPages && totalPages > 0) {
            currentPage = totalPages;
        }

        int offset = (currentPage - 1) * PRODUCTS_PER_PAGE;

        List<Product> products = productDao.getAllOnShelfProducts(keyword, offset, PRODUCTS_PER_PAGE); // 传递关键词给DAO

        request.setAttribute("products", products);
        request.setAttribute("currentPage", currentPage);
        request.setAttribute("totalPages", totalPages);
        request.setAttribute("keyword", keyword); // 将关键词传回JSP，以便搜索框保留内容

        request.getRequestDispatcher("index.jsp").forward(request, response);
    }
} 